﻿using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace PrototypePattern.AppExample
{
    [Serializable]
    class WeeklyLog
    {
        #region 成员变量
        public Attachment Attachment { get; set; }

        public string Name { get; set; }

        public string Date { get; set; }

        public string Content { get; set; }
        #endregion

        /*
        //使用MemberwiseClone()方法实现浅克隆
        public WeeklyLog Clone()
        {
            return this.MemberwiseClone() as WeeklyLog;
        }
         */

        /// <summary>
        /// 使用序列化方式实现深克隆
        /// </summary>
        /// <returns></returns>
        public WeeklyLog Clone()
        {
            WeeklyLog clone = null;
            BinaryFormatter formatter = new BinaryFormatter();
            using (FileStream fs = new FileStream("Temp.dat", FileMode.Create))
            {
                try
                {
                    formatter.Serialize(fs, this);
                }
                catch (SerializationException exp)
                {
                    Console.WriteLine("Failed to serialize. Reason: " + exp.Message);
                    throw;
                }
            }

            BinaryFormatter formatter1 = new BinaryFormatter();
            using (FileStream fs1 = new FileStream("Temp.dat", FileMode.Open))
            {
                try
                {
                    clone = formatter1.Deserialize(fs1) as WeeklyLog;
                }
                catch (SerializationException exp)
                {
                    Console.WriteLine("Failed to deserialize. Reason: " + exp.Message);
                    throw;
                }
            }

            return clone;
        }
    }
}
